import { t } from 'i18next'
import { SelectedMtModel, SelectMtEntity } from './translator'
import { CONSTANT } from './utils/utils'
import { Alert } from '@/components/Alert'
import { fetchSimpleCascadeTypeAndCheckAddTemplateMap } from '@/api/addMt'
import { useSelectedStore } from './blocks/selected/store'
import { useMtAddStore } from './store'

type IAccountType = typeof CONSTANT.accountType[keyof typeof CONSTANT.accountType]

const SFU_EXCEPT_ACCOUNTTYPE: IAccountType[] = [
	CONSTANT.accountType.IP,
	CONSTANT.accountType.e164Ip,
	CONSTANT.accountType.phone,
	CONSTANT.accountType.template,
]

export const useSubmit = () => {
	const onOk = async () => {
		const list = useSelectedStore.getState().selectedList
		const curTemplateE164 = useMtAddStore.getState().curTemplateE164
		const meetingType = useMtAddStore.getState().meetingType
		const smcuMtid = useMtAddStore.getState().currentCascadeId
		const onSubmit = useMtAddStore.getState().onSubmit
		//sfu 会议不支持级联，并且当前是sfu会议需要删去ip和phone，模板，并且不能级联
		let sfuMeetingsList: SelectedMtModel[] = list.filter((x) => x.attr.meetingType === 2)
		if (sfuMeetingsList.length > 0) {
			let name = sfuMeetingsList.map((x) => x.item.name).join(',')
			Alert(t('{{name}}的会议类型不支持级联呼叫。', { name: name }))
		}
		let selectedList: Required<Omit<SelectMtEntity, 'meetingType'>>[] = list
			.filter((x) => x.attr.meetingType !== 2)
			.filter((x) => !(meetingType === 2 && SFU_EXCEPT_ACCOUNTTYPE.includes(x.item.accountType as IAccountType)))
			.map((x) => ({
				account: x.item.account,
				accountType: x.item.accountType,
				name: x.item.name,
				bitrate: x.item.bitrate,
				bitrateType: x.item.bitrateType,
				protocol: x.item.protocol,
				portrait: x.item.portrait,
				moid: x.item.moid,
				e164: x.item.e164,
				mobilePhone: x.item.mobilePhone,
				workPhone: x.item.workPhone,
				interactiveMt: x.attr.isInteractiveMt ? 1 : 0,
				oftenMt: x.attr.isOftenMt ? 1 : 0,
			}))
		let selectedTemplateList = selectedList.filter((x) => x.accountType === CONSTANT.accountType.template)
		if (selectedTemplateList.length > 0) {
			//检验模板是否可以加入
			const res = await fetchSimpleCascadeTypeAndCheckAddTemplateMap({
				cur_template_e164: curTemplateE164,
				cascade_e164s: selectedTemplateList.map((x) => x.account).join(','),
			})
			if (res) {
				const { cascade_type: cascadeType, template_can_add } = res
				let canNotAdd = []
				for (const item in template_can_add) {
					if (!template_can_add[item]) {
						let x = selectedTemplateList.find((x) => x.account === item)
						if (x) canNotAdd.push(x.name || x.account)
					}
				}
				if (canNotAdd.length > 0) {
					Alert(t('新加级联节点:{{canNotAdd}}不能添加！', { canNotAdd: canNotAdd.join(',') }))
					return
				}
				onSubmit({ selectedList, cascadeType, smcuMtid })
			} else {
				onSubmit({ selectedList, smcuMtid })
			}
		} else {
			onSubmit({ selectedList, smcuMtid })
		}
	}
	return { onOk }
}
